import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {InfoCircleOutlined} from "@ant-design/icons";
import { Input, Modal, InputNumber, Upload, Button, Icon, Select, Radio, Tooltip, Table, Switch, Checkbox, message} from 'antd';
import { formatMessage, FormattedMessage} from 'umi-plugin-react/locale';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import React, { useState,useEffect } from 'react';
import styles from '../style.less'
import ColorPicker from 'rc-color-picker';
import 'rc-color-picker/assets/index.css';
import DataLang from './DataLang';

import CryptoJS from 'crypto-js';


// 导入自定义组件1
import PreviewForm from '@/components/PreviewForm';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import * as TsxHelper from '@/helpers/TsxHelper';

// 常量
const { TextArea } = Input;
const FormItem = Form.Item;
const Option = Select;

// 定义: 数据表单属性
interface DataFormProps extends FormComponentProps {
  dataModalVisible: boolean;
  isUpdate: boolean
  dataFormValues: any
  common: any
  dataList: any
  onSubmit: (fieldsValue: any) => any;
  onCancel: () => void;
}

// 数据表单
const DataForm: React.FC<DataFormProps> = props => {
  // 组件属性
  const { dataModalVisible, form, onSubmit: handleSubmit, onCancel,
    common, isUpdate,dataFormValues,dataList } = props;

  // 图片状态
  const [picture, setPicture] = useState<any[]>([]);
  const [uploadChanged, setUploadChanged] = useState<boolean>(false);
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');

  const [continent,setContinent] = useState<any>('');
  const [nation,setNation] = useState<any>('');

  const [dataLangModalVisible, handleDataModalVisible] = useState<boolean>(false);
  const [fieldTitle, setFieldTitle] = useState<any>('');
  console.log(dataList);
  const [siteNameJson, setSiteNameJson] = useState<any>(dataFormValues?.lang_json_arr || []);
  console.log(siteNameJson);
  const [moreLang, setMoreLang] = useState<any>([]);
  

  const [nameListLang, setnameList] = useState<any>(dataFormValues?.lang_json_arr || common?.languagesOption);

  useEffect(()=>{
    if(isUpdate){
      setSiteNameJson(dataFormValues?.lang_json_arr || []);
      setnameList(dataFormValues?.lang_json_arr || common?.languagesOption);
    }
    
  },[dataFormValues,common])

  //提交表单
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if(picture.length > 0){
        fieldsValue.icon_file_id   = picture[0].file_id
        fieldsValue.icon_file_url  = picture[0].file_url
      }
      // 如果是更新
      if(isUpdate){
        fieldsValue.id = dataFormValues.id;
      }
      if(!fieldsValue.is_enable_color) fieldsValue.nickname_color = null;
      delete fieldsValue.is_enable_color
      // fieldsValue.name = siteNameJson.length>0?siteNameJson[0].lang_content : '';
      fieldsValue.lang_json = JSON.stringify(siteNameJson);
      
      fieldsValue.is_display_name = fieldsValue.display_identifying.indexOf('is_display_name') > -1 ? 1 : 0;
      fieldsValue.is_display_icon = fieldsValue.display_identifying.indexOf('is_display_icon') > -1 ? 1 : 0;
      console.log("submit fields ", fieldsValue)

      // 如果更新成功之后，重置表单
      // handleSubmit(fieldsValue);
      handleSubmit(fieldsValue).then((success:any) => {
        console.log('handleSubmit then success is ', success)
        if(success){
          form.resetFields()
          setPicture([]);
          setSiteNameJson([]);
        }
      })
    });
  };


  // 设置上传文件值
  const setUploadFile = (fileList:any) => {
    setUploadChanged(true)
    if(fileList.length>0 && fileList[0].response && fileList[0].response?.code != 0){
      message.error(fileList[0].response.message);
      return
    }
    let fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if(fileArr.length > 0){
      setPicture(fileArr)
      setPreviewImg(fileArr[0].file_url)
    }else if(fileArr.length === 0){
      console.log('set picture []')
      setPicture([])
    }
  }

    // 表单提交
    const handleSubmitDataForm = (value:any,title:any) => {
      console.log(value,111)
      setnameList(value)
      if(title == "name"){
        setSiteNameJson(value);
      }
      handleDataModalVisible(false)
    }

  // 初始化变量
  const token = BdHelper.getBdToken()

  // 编辑时初始化 picture
  const defaultPicture = DataHelper.buildFileByUrl(dataFormValues.icon_file_url)

  // 是否展示图片上传按钮
  const showUploadButton = DataHelper.showUploadBtn(isUpdate, picture, defaultPicture, uploadChanged)

  const userInfo = localStorage.getItem('user-login-info');
  let fresnsClient = eval("(" + userInfo + ")");
  const timestamp = new Date().getTime().toString().substr(0,10);
  var md5String = `appId=${fresnsClient?.app_id}&platform=${fresnsClient?.platform}&timestamp=${timestamp}&key=${fresnsClient?.app_secret}`;
  

  // 弹出框
  // @ts-ignore
  return <Modal
    destroyOnClose
    title={'角色管理'}
    width={"40%"}
    visible={dataModalVisible}
    onOk={okHandle}
    onCancel={() => onCancel()}
  >

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'ranknum' })}>
      {form.getFieldDecorator('rank_num', {
        initialValue: isUpdate ? dataFormValues.rank_num : 88,
        rules: [{ required: true, message: '请输入！',}],
      })(<InputNumber placeholder={formatMessage({ id: 'app.base.please_input' })} style={{ width: '100%' }}/>)}
    </FormItem>

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: '角色类型' })}>
      {form.getFieldDecorator('type', {
        initialValue: isUpdate ? dataFormValues?.type && (dataFormValues?.type).toString() : undefined,
         rules: [{ required: true, message: '请选择！',}],
      })(<Select placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
        {common.typeOption && TsxHelper.buildNameSelectOption(common.typeOption)}
      </Select>)}
    </FormItem>

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label='是否启用昵称颜色'>
      {form.getFieldDecorator('is_enable_color', {
        initialValue: true,
        valuePropName: 'checked',
      })(<Switch checkedChildren={formatMessage({ id: 'app.base.is-enable.true' })} unCheckedChildren={formatMessage({ id: 'app.base.is-enable.close' })} />)}
    </FormItem>

    {
      form.getFieldValue('is_enable_color') == true &&
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}  className={styles.colorPickerBox}
        label={
          <span>
            <FormattedMessage id="昵称颜色" />
            <em className={styles.optional}>
              <Tooltip title={<FormattedMessage id="该角色的用户昵称颜色" />}>
                <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
              </Tooltip>
            </em>
          </span>
        }>
      {form.getFieldDecorator('nickname_color', {
        initialValue: isUpdate ? dataFormValues.nickname_color : '#1990FF',
        // rules: [{ required: true, message: '请选择颜色！', }],
        valuePropName: 'color',
        getValueFromEvent: e => e.color,
      })(<ColorPicker  />)}
    </FormItem>
    }
    

    <FormItem
      label={
        <span >
          <FormattedMessage id="角色名" />
        </span>
      }
      labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
      {form.getFieldDecorator('name', {
          initialValue: siteNameJson.length > 0 ? siteNameJson[0].lang_content : '',
          rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
        })(<Input style={{cursor:"pointer"}} readOnly placeholder={'角色名'} onClick={() => {
            setFieldTitle('name');
            if(siteNameJson && siteNameJson.length>0){
              setnameList(siteNameJson);
            }else{
              setnameList(JSON.parse(JSON.stringify(common?.languagesOption)));
            }
            handleDataModalVisible(true);
           }}/>)}
    </FormItem>

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: '角色图标' })}>
      {form.getFieldDecorator('picture', {
        // initialValue: defaultPicture,
        // rules: [{required: true, message: '请上传图片'}],
      })(
        <Upload
          listType={'picture'}
          className={'upload-list-inline'}
          action="/api/admin/tweetfiles/upload"
          defaultFileList={defaultPicture}
          beforeUpload={(file) => {
            console.log('before upload file type:', file.type)
            // todo: 这里可以对上传文件类型做限制
            return true;
          }}
          data={{ table_type:3, table_name: 'member_roles', }}
          onRemove={() => setPicture([])}
          onChange={(changeObj) => setUploadFile(changeObj.fileList)}
          onPreview={() => {setPreviewImg(dataFormValues?.icon_file_url );handlePreviewModalVisible(true)}}
          headers={{
            Authorization: `Bearer ${token}`,
            'platform': fresnsClient?.platform,
            'timestamp': timestamp,
            'appId': fresnsClient?.app_id,
            'sign':  CryptoJS.MD5(md5String).toString(),
          }}
        >
          {
            showUploadButton ? (
              <Button>
                <Icon type="upload"/> {formatMessage({ id: 'app.base.upload' })}
              </Button>
            ) : null
          }
        </Upload>
      )}
    </FormItem>

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} style={{marginBottom: 15}}
        label={
          <span>
            <FormattedMessage id="显示标识" />
            <em className={styles.optional}>
              <Tooltip title={<FormattedMessage id="账号设置密码中必须存在所选字符类型，不选则为无限制" />}>
                <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
              </Tooltip>
            </em>
          </span>
        }>
        {form.getFieldDecorator('display_identifying', {
          initialValue: isUpdate ? [dataFormValues.is_display_name == 1 ? 'is_display_name' : '',dataFormValues.is_display_icon == 1 ? 'is_display_icon' : ''] : '',
          // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
        })(<Checkbox.Group  onChange={(list)=>{console.log(list)}}>
          <Checkbox value={'is_display_name'}>角色名</Checkbox>
          <Checkbox value={'is_display_icon'}>角色图标</Checkbox>
        </Checkbox.Group>)}
    </FormItem>

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label='是否启用'>
      {form.getFieldDecorator('is_enable', {
        initialValue: isUpdate ? dataFormValues.is_enable : false,
        valuePropName: 'checked',
      })(<Switch checkedChildren={formatMessage({ id: 'app.base.is-enable.true' })} unCheckedChildren={formatMessage({ id: 'app.base.is-enable.close' })} />)}
    </FormItem>

    <DataLang
        dataModalVisible={dataLangModalVisible}
        isUpdate={isUpdate}
        dataFormValues={dataFormValues}
        common={common || {}}
        morelangList={dataList}
        nameList={nameListLang}
        title={fieldTitle}
        onSubmit={handleSubmitDataForm}
        onCancel={() => handleDataModalVisible(false)}
    />
    {
      previewModelVisible && (
        <PreviewForm
          previewModelVisible={previewModelVisible}
          onVisibleModel={handlePreviewModalVisible}
          previewImg={previewImg}
        />
      )
    }
  </Modal>;
};

export default Form.create<DataFormProps>()(DataForm);
